package com.uduemc.biso.node.web.api.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.common.extities.CTemplateListData;
import com.uduemc.biso.core.common.extities.ctemplatelistdata.CTemplateItemData;
import com.uduemc.biso.core.extities.center.Agent;
import com.uduemc.biso.core.extities.center.AgentLoginDomain;
import com.uduemc.biso.core.extities.center.AgentNodeServerDomain;
import com.uduemc.biso.core.extities.center.AgentOemNodepage;
import com.uduemc.biso.core.extities.center.SiteRenew;
import com.uduemc.biso.core.extities.center.SysApiAccess;
import com.uduemc.biso.core.extities.center.SysHostType;
import com.uduemc.biso.core.extities.center.SysLanguage;
import com.uduemc.biso.core.extities.center.SysServer;
import com.uduemc.biso.core.extities.center.SysTemplateModel;
import com.uduemc.biso.core.extities.center.custom.centerconfig.CenterConfigAiSetup;
import com.uduemc.biso.core.extities.pojo.ICP35;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.config.SpringContextUtil;
import com.uduemc.biso.node.web.api.pojo.ResponseSiteRenew;
import com.uduemc.biso.node.web.api.service.CenterService;
import com.uduemc.biso.node.web.component.CenterFunction;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class CenterServiceImpl implements CenterService {

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private CenterFunction centerFunction;

	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private SpringContextUtil springContextUtil;

	@Override
	public List<SysLanguage> getAllLanguage() {
		String KEY = globalProperties.getCenterRedisKey().getSysLanguageFindAllKey();
		@SuppressWarnings("unchecked")
		List<SysLanguage> sysLanguageList = (List<SysLanguage>) redisUtil.get(KEY);
		if (CollectionUtils.isEmpty(sysLanguageList)) {
			log.info("获取 sysLanguageList 数据存入缓存中");
			sysLanguageList = centerFunction.getAllLanguage();
			if (!CollectionUtils.isEmpty(sysLanguageList)) {
				redisUtil.set(KEY, sysLanguageList, 3600 * 24 * 10L);
			}
		}
		return sysLanguageList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SysHostType> getAllSysHostType() {
		String KEY = globalProperties.getCenterRedisKey().getSysHostTypeFindAllKey();
		List<SysHostType> sysHostTypeList = (List<SysHostType>) redisUtil.get(KEY);
		if (CollectionUtils.isEmpty(sysHostTypeList)) {
			log.info("获取 sysHostTypeList 数据存入缓存中");
			sysHostTypeList = centerFunction.getAllHostType();
			if (!CollectionUtils.isEmpty(sysHostTypeList)) {
				redisUtil.set(KEY, sysHostTypeList, 3600 * 5);
			}
		}
		return sysHostTypeList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SysServer> getAllSysServer() {
		String KEY = globalProperties.getCenterRedisKey().getSysServerFindOkAllKey();
		List<SysServer> sysServerList = (List<SysServer>) redisUtil.get(KEY);
		if (CollectionUtils.isEmpty(sysServerList)) {
			log.info("获取 sysServerList 数据存入缓存中");
			sysServerList = centerFunction.getAllSysServer();
			if (!CollectionUtils.isEmpty(sysServerList)) {
				redisUtil.set(KEY, sysServerList, 3600 * 5);
			}
		}
		return sysServerList;
	}

	@Override
	public SysServer selfSysServer() {
		String KEY = globalProperties.getCenterRedisKey().getSysServerFindOkDefaultByIp();
		SysServer sysServer = (SysServer) redisUtil.get(KEY);
		if (sysServer == null) {
			log.info("获取 sysServer 数据存入缓存中");
			if (springContextUtil.local()) {
				sysServer = centerFunction.selfSysServer("10.35.60.80");
			} else {
				sysServer = centerFunction.selfSysServer();
			}

			if (sysServer != null) {
				redisUtil.set(KEY, sysServer, 3600 * 24 * 30);
			}
		}
		return sysServer;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SysTemplateModel> getAllSysTemplateModel() {
		String KEY = globalProperties.getCenterRedisKey().getSysTemplateModelFindAllKey();
		List<SysTemplateModel> listSysTemplateModel = (List<SysTemplateModel>) redisUtil.get(KEY);
		if (CollectionUtils.isEmpty(listSysTemplateModel)) {
			log.info("获取sysTemplateModelList 数据存入缓存中");
			listSysTemplateModel = centerFunction.getAllSysTemplateModel();
			if (!CollectionUtils.isEmpty(listSysTemplateModel)) {
				redisUtil.set(KEY, listSysTemplateModel, 3600 * 5);
			}
		}
		return listSysTemplateModel;
	}

	@Override
	public SysTemplateModel getSysTemplateModel(long templateId) {
		List<SysTemplateModel> allSysTemplateModel = getAllSysTemplateModel();
		SysTemplateModel sysTemplateModel = null;
		for (SysTemplateModel sysTemplate : allSysTemplateModel) {
			if (sysTemplate.getId().longValue() == templateId) {
				sysTemplateModel = sysTemplate;
			}
		}
		return sysTemplateModel;
	}

	@Override
	public CTemplateListData getCenterApiTemplateData(String templatename, long typeId, int page, int pageSize) {
		CTemplateListData cTemplateListData = centerFunction.getCTemplateListData(templatename, typeId, page, pageSize);
		log.info("cTemplateListData: " + cTemplateListData.toString());
		if (!CollectionUtils.isEmpty(cTemplateListData.getRows())) {
			for (CTemplateItemData itemData : cTemplateListData.getRows()) {
				String pcimage = itemData.getPcimage();
				String wapimage = itemData.getWapimage();
				itemData.setPcimage(globalProperties.getCenter().getCenterApiHost() + pcimage);
				itemData.setWapimage(globalProperties.getCenter().getCenterApiHost() + wapimage);
			}
		}
		return cTemplateListData;
	}

	@Override
	public CTemplateItemData getCenterApiTemplateItemData(long templateId) {
		CTemplateItemData cTemplateItemData = centerFunction.getCTemplateItemData(templateId);
		return cTemplateItemData;
	}

	@Override
	public CTemplateItemData getCenterApiTemplateItemDataByUrl(String domain) {
		CTemplateItemData cTemplateItemData = centerFunction.getCTemplateItemDataByUrl(domain);
		return cTemplateItemData;
	}

	@Override
	public List<SysApiAccess> getOkallowAccessMaster() {
		List<SysApiAccess> listSysApiAccess = centerFunction.getOkallowAccessMaster();
		return listSysApiAccess;
	}

	@Override
	public int updatePassword(long userId, String opassword, String password) {
		return centerFunction.updateUserPassword(userId, opassword, password);
	}

	@Override
	public ICP35 getIcpDomain(String domain) {
		ICP35 icp = centerFunction.getIcpdomain(domain);
		return icp;
	}

	@Override
	public Agent agentInfo(long agentId) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Agent agent = centerFunction.agentInfo(agentId);
		return agent;
	}

	@Override
	public AgentOemNodepage getAgentOemNodepage(long agentId) throws IOException {
		return centerFunction.getAgentOemNodepage(agentId);
	}

	@Override
	public AgentLoginDomain getAgentLoginDomain(long agentId) throws IOException {
		return centerFunction.getAgentLoginDomain(agentId);
	}

	@Override
	public AgentNodeServerDomain getAgentNodeServerDomainByDomainName(String domainName) throws IOException {
		return centerFunction.getAgentNodeServerDomainByDomainName(domainName);
	}

	@Override
	public AgentNodeServerDomain getAgentNodeServerDomainByUniversalDomainName(String universalDomainName) throws IOException {
		return centerFunction.getAgentNodeServerDomainByUniversalDomainName(universalDomainName);
	}

	@Override
	public List<String> getAdWords() throws IOException {
		String KEY = globalProperties.getCenterRedisKey().getCenterConfigAdwords();
		@SuppressWarnings("unchecked")
		List<String> adwords = (List<String>) redisUtil.get(KEY);
		if (CollUtil.isEmpty(adwords)) {
			adwords = centerFunction.getAdWords();
			if (!CollUtil.isEmpty(adwords)) {
				redisUtil.set(KEY, adwords, 3600 * 24 * 10L);
			}
		}
		return adwords;
	}

	@Override
	public ResponseSiteRenew lastSiteRenew() throws IOException {
		SiteRenew siteRenew = centerFunction.lastSiteRenew();

		// 替换content中的图片链接地址，使其图片显示生效
		String content = siteRenew.getContent();
		Pattern pattern = Pattern.compile("src=\"(/site/filemanage/file/(.*?))\"", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
		Matcher matcher = pattern.matcher(content);
		String imgSrc = "";
		while (matcher.find()) {
			imgSrc = matcher.group(1);
			if (StrUtil.isBlank(imgSrc)) {
				continue;
			}
			content = StrUtil.replace(content, imgSrc, "//" + globalProperties.getCenter().getCenterApiDomain() + imgSrc);
		}
		siteRenew.setContent(content);

		ResponseSiteRenew responseSiteRenew = ResponseSiteRenew.makeResponseSiteRenew(siteRenew);
		responseSiteRenew.setMore("//" + globalProperties.getCenter().getCenterApiDomain() + "/help/renew.html");
		return responseSiteRenew;
	}

	@Override
	public boolean appendTemplateSuggestion(String name, String contactInformation, String industry, String referenceLink, String content) throws IOException {
		Long customerUserId = requestHolder != null && requestHolder.getCurrentLoginNode() != null
				? requestHolder.getCurrentLoginNode().getCustomerUser().getId()
				: 0;
		Map<String, String> valuePair = new HashMap<>();
		valuePair.put("customerUserId", String.valueOf(customerUserId));
		valuePair.put("name", name);
		valuePair.put("contactInformation", contactInformation);
		valuePair.put("industry", industry);
		valuePair.put("referenceLink", referenceLink);
		valuePair.put("content", content);

		return centerFunction.appendTemplateSuggestion(valuePair);
	}

	@Override
	public CenterConfigAiSetup getAiSetup() throws IOException {
		String KEY = globalProperties.getCenterRedisKey().getCenterConfigAiSetup();
		CenterConfigAiSetup aiSetup = (CenterConfigAiSetup) redisUtil.get(KEY);
		if (aiSetup == null) {
			aiSetup = centerFunction.getAiSetup();
			if (aiSetup != null) {
				redisUtil.set(KEY, aiSetup, 1800);
			}
		}
		return aiSetup;
	}

	@Override
	public void resetAiSetup() throws IOException {
		String KEY = globalProperties.getCenterRedisKey().getCenterConfigAiSetup();
		redisUtil.del(KEY);
		getAiSetup();
	}
}
